<template>
  <view class="search-container">
    <view class="search-header">
      <view class="search-input">
        <text class="search-icon">🔍</text>
        <input 
          type="text" 
          v-model="searchKey" 
          placeholder="搜索医生、疾病、药品" 
          @confirm="handleSearch"
          @input="handleInput"
        />
        <text class="clear-icon" v-if="searchKey" @tap="clearSearch">✕</text>
      </view>
      <text class="cancel-btn" @tap="goBack">取消</text>
    </view>
    
    <!-- 搜索历史 -->
    <view class="search-history" v-if="!searchKey && searchHistory.length > 0">
      <view class="section-header">
        <text class="title">搜索历史</text>
        <text class="clear" @tap="clearHistory">清空</text>
      </view>
      <view class="history-list">
        <text 
          class="history-item" 
          v-for="(item, index) in searchHistory" 
          :key="index"
          @tap="useHistory(item)"
        >{{ item }}</text>
      </view>
    </view>
    
    <!-- 热门搜索 -->
    <view class="hot-search" v-if="!searchKey">
      <view class="section-header">
        <text class="title">热门搜索</text>
      </view>
      <view class="hot-list">
        <text 
          class="hot-item" 
          v-for="(item, index) in hotSearches" 
          :key="index"
          @tap="useHot(item)"
        >{{ item }}</text>
      </view>
    </view>
    
    <!-- 搜索结果 -->
    <view class="search-result" v-if="searchKey">
      <view class="result-tabs">
        <text 
          class="tab-item" 
          v-for="(tab, index) in tabs" 
          :key="index"
          :class="{ active: currentTab === index }"
          @tap="switchTab(index)"
        >{{ tab }}</text>
      </view>
      
      <view class="result-list">
        <!-- 医生列表 -->
        <view class="doctor-list" v-if="currentTab === 0">
          <view class="doctor-item" v-for="(doctor, index) in doctorResults" :key="index" @tap="goToDoctor(doctor)">
            <view class="doctor-avatar">{{ doctor.name[0] }}</view>
            <view class="doctor-info">
              <text class="name">{{ doctor.name }}</text>
              <text class="title">{{ doctor.title }}</text>
            </view>
          </view>
        </view>
        
        <!-- 疾病列表 -->
        <view class="disease-list" v-if="currentTab === 1">
          <view class="disease-item" v-for="(disease, index) in diseaseResults" :key="index" @tap="goToDisease(disease)">
            <text class="name">{{ disease.name }}</text>
            <text class="desc">{{ disease.description }}</text>
          </view>
        </view>
        
        <!-- 药品列表 -->
        <view class="medicine-list" v-if="currentTab === 2">
          <view class="medicine-item" v-for="(medicine, index) in medicineResults" :key="index" @tap="goToMedicine(medicine)">
            <text class="name">{{ medicine.name }}</text>
            <text class="desc">{{ medicine.description }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { searchApi } from '@/api'

export default {
  data() {
    return {
      searchKey: '',
      searchHistory: [],
      hotSearches: ['感冒', '发烧', '头痛', '咳嗽', '高血压', '糖尿病'],
      tabs: ['医生', '疾病', '药品'],
      currentTab: 0,
      doctorResults: [],
      diseaseResults: [],
      medicineResults: []
    }
  },
  onLoad() {
    // 获取搜索历史
    const history = uni.getStorageSync('searchHistory')
    if (history) {
      this.searchHistory = JSON.parse(history)
    }
  },
  methods: {
    handleInput() {
      // 实现输入防抖
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        this.search()
      }, 500)
    },
    
    async search() {
      if (!this.searchKey) {
        this.clearResults()
        return
      }
      
      try {
        // 这里后期会替换为 Elasticsearch 搜索
        const res = await searchApi.search({
          keyword: this.searchKey,
          type: this.currentTab
        })
        
        // 根据当前tab显示对应结果
        switch (this.currentTab) {
          case 0:
            this.doctorResults = res.data.doctors || []
            break
          case 1:
            this.diseaseResults = res.data.diseases || []
            break
          case 2:
            this.medicineResults = res.data.medicines || []
            break
        }
        
        // 保存搜索历史
        this.saveHistory()
      } catch (error) {
        console.error('搜索失败:', error)
        uni.showToast({
          title: '搜索失败',
          icon: 'none'
        })
      }
    },
    
    handleSearch() {
      this.search()
    },
    
    clearSearch() {
      this.searchKey = ''
      this.clearResults()
    },
    
    clearResults() {
      this.doctorResults = []
      this.diseaseResults = []
      this.medicineResults = []
    },
    
    switchTab(index) {
      this.currentTab = index
      this.search()
    },
    
    saveHistory() {
      if (!this.searchKey) return
      
      // 移除重复项
      const index = this.searchHistory.indexOf(this.searchKey)
      if (index > -1) {
        this.searchHistory.splice(index, 1)
      }
      
      // 添加到开头
      this.searchHistory.unshift(this.searchKey)
      
      // 限制历史记录数量
      if (this.searchHistory.length > 10) {
        this.searchHistory.pop()
      }
      
      // 保存到本地存储
      uni.setStorageSync('searchHistory', JSON.stringify(this.searchHistory))
    },
    
    clearHistory() {
      this.searchHistory = []
      uni.removeStorageSync('searchHistory')
    },
    
    useHistory(keyword) {
      this.searchKey = keyword
      this.search()
    },
    
    useHot(keyword) {
      this.searchKey = keyword
      this.search()
    },
    
    goToDoctor(doctor) {
      uni.navigateTo({
        url: `/pages/doctor/doctor?id=${doctor.id}`
      })
    },
    
    goToDisease(disease) {
      uni.navigateTo({
        url: `/pages/disease/disease?id=${disease.id}`
      })
    },
    
    goToMedicine(medicine) {
      uni.navigateTo({
        url: `/pages/medicine/medicine?id=${medicine.id}`
      })
    },
    
    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss">
.search-container {
  min-height: 100vh;
  background: #fff;
  
  .search-header {
    display: flex;
    align-items: center;
    padding: 100rpx;
    background: #fff;
    position: sticky;
    top: 10;
    z-index: 100;
    
    .search-input {
      flex: 1;
      display: flex;
      align-items: center;
      background: #f5f5f5;
      height: 100rpx;
      border-radius: 36rpx;
      padding: 0 20rpx;
      margin-right: 20rpx;
      
      .search-icon {
        font-size: 32rpx;
        margin-right: 10rpx;
      }
      
      input {
        flex: 1;
        height: 100%;
        font-size: 28rpx;
      }
      
      .clear-icon {
        font-size: 32rpx;
        color: #999;
        padding: 10rpx;
      }
    }
    
    .cancel-btn {
      font-size: 28rpx;
      color: #666;
    }
  }
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    
    .title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .clear {
      font-size: 28rpx;
      color: #999;
    }
  }
  
  .search-history {
    .history-list {
      padding: 0 30rpx;
      display: flex;
      flex-wrap: wrap;
      
      .history-item {
        background: #f5f5f5;
        padding: 10rpx 20rpx;
        border-radius: 30rpx;
        margin: 0 20rpx 20rpx 0;
        font-size: 28rpx;
        color: #666;
      }
    }
  }
  
  .hot-search {
    .hot-list {
      padding: 0 30rpx;
      display: flex;
      flex-wrap: wrap;
      
      .hot-item {
        background: #f5f5f5;
        padding: 10rpx 20rpx;
        border-radius: 30rpx;
        margin: 0 20rpx 20rpx 0;
        font-size: 28rpx;
        color: #666;
      }
    }
  }
  
  .search-result {
    .result-tabs {
      display: flex;
      border-bottom: 1rpx solid #eee;
      
      .tab-item {
        flex: 1;
        text-align: center;
        padding: 20rpx 0;
        font-size: 28rpx;
        color: #666;
        position: relative;
        
        &.active {
          color: #007AFF;
          font-weight: bold;
          
          &::after {
            content: '';
            position: absolute;
            left: 50%;
            bottom: 0;
            transform: translateX(-50%);
            width: 40rpx;
            height: 4rpx;
            background: #007AFF;
            border-radius: 2rpx;
          }
        }
      }
    }
    
    .result-list {
      padding: 20rpx;
      
      .doctor-list {
        .doctor-item {
          display: flex;
          align-items: center;
          padding: 20rpx;
          border-bottom: 1rpx solid #eee;
          
          .doctor-avatar {
            width: 80rpx;
            height: 80rpx;
            border-radius: 40rpx;
            background: #007AFF;
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 32rpx;
            margin-right: 20rpx;
          }
          
          .doctor-info {
            flex: 1;
            
            .name {
              font-size: 30rpx;
              color: #333;
              margin-bottom: 6rpx;
              display: block;
            }
            
            .title {
              font-size: 24rpx;
              color: #666;
            }
          }
        }
      }
      
      .disease-list,
      .medicine-list {
        .disease-item,
        .medicine-item {
          padding: 20rpx;
          border-bottom: 1rpx solid #eee;
          
          .name {
            font-size: 30rpx;
            color: #333;
            margin-bottom: 6rpx;
            display: block;
          }
          
          .desc {
            font-size: 24rpx;
            color: #999;
          }
        }
      }
    }
  }
}
</style> 